package com.example.test01.mysql_test.web;

import com.alibaba.excel.EasyExcel;
import com.example.test01.mysql_test.entity.StudentEntity;
import com.example.test01.mysql_test.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Describle:
 * ClassName: ImportController
 * Author: duende
 * DateTime: 2022/4/17 20:10
 */
@RestController
public class ImportController {

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 表格导入
     */
    @PostMapping("/tableImport")
    @Transactional
    public String tableImport(@RequestParam("multipartFile") MultipartFile multipartFile) throws IOException {
        //读取上传文件数据转换成输入流
        InputStream inputStream = multipartFile.getInputStream();
        //吧上传文件的输入流  储存的list
        List<Object> list = EasyExcel.read(inputStream).doReadAllSync();
        //里面的数据是{0:1,1:'AmdYes',2:'intel Yes'}
        for (Object a : list) {
            Map<Integer, String> map = (HashMap<Integer, String>) a;
//            if (map.size() > 4) {
//                return R.fail("表格信息有误");
//            }
            //时间的格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            //获取map 里的数据
            StudentEntity recordCarAll = new StudentEntity();
            recordCarAll.setName(map.get(0));
            recordCarAll.setYuwen(map.get(1));
            recordCarAll.setShuxue(map.get(2));
            recordCarAll.setYingyu(map.get(3));
            recordCarAll.setZonghe(map.get(4));
//            String startTime = map.get(2);
//            String endTime = map.get(3);
//            Date startTimeDate = null;
//            Date endTimeDate = null;
            //对时间进行解析如果不对这抛出异常
//            try {
//                startTimeDate = df.parse(startTime);
//                endTimeDate = df.parse(endTime);
//            } catch (ParseException e) {
//                return R.fail("时间格式有错误");
//            }
//            recordCarAll.setStartTime(startTimeDate);
//            recordCarAll.setEndTime(endTimeDate);
            //对上传数据进行保存
            try {
                studentMapper.save(recordCarAll);
            } catch (Exception e) {
                throw new RuntimeException("导入异常");
            }
//            if (pd) {
//
//            } else {
//                throw new RuntimeException("");
//            }
        }

        return "导入成功";
    }



}
